package org.sosie2.client.other;

/**
 * author: gabriela
 */

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;

import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.NullProvider;
import org.apache.axis.message.SOAPBody;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.utils.XMLUtils;
import org.apache.log4j.Logger;
import org.sosie2.service.framework.Utils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;


public class WSLoggingClient
{
	public  static final String endPoint = "http://localhost:8080/axis/services/SOSIELoggerWS";
	
	public static final String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
	"<m:loggingmessage \r\n" + 
	"xmlns:m=\"http://localhost:8080/axis/services/MyLoggerService\">\r\n" + 
	"<m:gravity>" +
	"1"+
	"</m:gravity>"+
	"<m:message>"+
	"There is no spoon"+
	"</m:message>"+
	"</m:loggingmessage>" ;
	
	
	static Logger logger = Logger.getLogger(WSLoggingClient.class);
	public static Message SOAPmessage;
	
	public static void initializeContext()
	{
		MessageContext msgContext;
		
		AxisClient tmpEngine = new AxisClient(new NullProvider());
		msgContext = new MessageContext(tmpEngine);
		InputStream in = new ByteArrayInputStream(Utils.emptySoapMsg.getBytes());
		Message msg = new Message(in);
		msg.setMessageContext(msgContext);	 
		
		StringReader strReader = new StringReader(request);		
		
		try{
			logger.info("Getting to the request...");
			Document document = XMLUtils.newDocument(new InputSource(strReader));

			// Add request to SOAP body
			SOAPBody body = (SOAPBody) msg.getSOAPBody();					
			body.addDocument(document);
			
			SOAPmessage = msg;
			
			Utils.dumpXML("SOAPMessage:", SOAPmessage.getSOAPEnvelope().getAsDocument(),logger);
		}
		catch(Exception e)
		{
			logger.warn("Exception : " + e.getMessage());
		}
	}
	
	public static void main(String args[])
	{
		initializeContext();
			
		try{
			Service  service = new Service();
	        Call call = (Call) service.createCall();
	        call.setTargetEndpointAddress( new java.net.URL(endPoint));
			
			System.out.println("Sent request to LoggerService...");
			SOAPEnvelope response = (SOAPEnvelope)call.invoke(SOAPmessage);			

		}
		catch(Exception e)
		{
			logger.warn("Fault: " + e.getMessage());
			e.printStackTrace();
		}
	
	}
	
}

 